# 批量修改服务配置文件中的pkgPath的地址
import json
import os
import sys


def genePathPre(depth):
    result = ''
    for i in range(depth):
        result += '../'

    return result


def dealConfigFiles(path, depth, depthPath):
    dirs = os.listdir(path)

    for i in dirs:
        if os.path.isfile(path + '/' + i):
            # ns = ns + 1
            newPkgPath = genePathPre(depth) + 'package/' + depthPath
            changeAttr(path + '/' + i, 'pkgPath', newPkgPath)

            # MapServer文件路径
            newPkgPath = genePathPre(depth) + 'metadata/' + 'MapServer/MapServer.json'
            changeAttr(path + '/' + i, 'MapServerJSONPath', newPkgPath)

            # print('stop' + path + '/' + i)
        elif os.path.isdir(path + '/' + i):
            print('folder' + path + '/' + i)
            dealConfigFiles(path + '/' + i, depth + 1, depthPath + i + '/')


def changeAttr(path, key, val):
    with open(path, 'r', encoding='utf-8') as f:
        elem = json.load(f)
        if key == 'pkgPath':
            filename = elem[key][elem[key].rfind('/') + 1:]
            val += filename
        elif key == 'MapServerJSONPath':
            if key not in elem:
                return
        elem[key] = val

    with open(path, 'w', encoding='utf-8') as f:
        json.dump(elem, f, ensure_ascii=False, indent=4)


if len(sys.argv) != 2:
    print('参数异常')
    sys.exit(1)

pa = sys.argv[1]
pa = pa.replace('//', '/')

dealConfigFiles(pa, 1, '')